#include <iostream>
#include <cstdio>
#include <cstring>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <algorithm>

#pragma comment(lib, "ws2_32")
// Windows environment
#ifdef _WIN32
#include <winsock2.h> // Ensure this is included before windows.h
#include <ws2tcpip.h>
#define close closesocket
// Linux environment
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define closesocket close
#endif

std::vector<int> clients;  // 客户端列表
std::mutex clients_mutex;  // 线程同步锁

class TcpThread {
public:
    int client_sock = 0;
    std::atomic<bool> running{true};
    ~TcpThread() {
        closesocket(client_sock);
#ifdef _WIN32
        WSACleanup();
#endif
    }
    void Main() {
        std::thread sender(&TcpThread::sendToClient, this);
        char buff[1024] = {0};
        while (running) {
            memset(buff, 0, sizeof(buff));
            int recv_len = recv(client_sock, buff, sizeof(buff) - 1, 0);
            buff[recv_len] = '\0';
            std::cout << "Received->: " << buff;
            if (strstr(buff, "quit") != NULL) {
                const char re[] = "quit success!\n";
                send(client_sock, re, strlen(re), 0);
                running = false;
                break;
            }
            // broadcast to other
            std::lock_guard<std::mutex> lock(clients_mutex);
            for (auto it = clients.begin(); it != clients.end(); ) {
                if (*it != client_sock) {
                    if (send(*it, buff, recv_len, 0) == SOCKET_ERROR) {
                        std::cerr << "Send to client failed. Removing client: " << *it << std::endl;
                        it = clients.erase(it);
                    } else {
                        ++it;
                    }
                } else {
                    ++it;
                }
            }
        }

        // after quit, remove client
        {
            std::lock_guard<std::mutex> lock(clients_mutex);
            clients.erase(std::remove(clients.begin(), clients.end(), client_sock), clients.end());
        }

        sender.join();
        delete this;
    }

    void sendToClient() {
        char buff[1024] = {0};
        while (running) {
            memset(buff, 0, sizeof(buff));
            std::cin.getline(buff, sizeof(buff) - 1);
            if (strcmp(buff, "quit") == 0) {
                running = false;
                break;
            }
            int buff_len = strlen(buff);
            buff[buff_len] = '\n';
            buff[buff_len+1] = '\r';
            // Broadcast
            std::lock_guard<std::mutex> lock(clients_mutex);
            for (auto it = clients.begin(); it != clients.end(); ) {
                if (send(*it, buff, strlen(buff), 0) == SOCKET_ERROR) {
                    std::cerr << "Send to client failed. Removing client: " << *it << std::endl;
                    it = clients.erase(it);
                } else {
                    ++it;
                }
            }
        }
    }
};

int main(int argc, char *argv[]) {
#ifdef _WIN32
    WSAData ws;
    if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) {
        std::cerr << "WSAStartup failed" << std::endl;
        return 1;
    }
#endif
    // Create socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET) {
        std::cerr << "Create socket failed" << std::endl;
#ifdef _WIN32
        WSACleanup();
#endif
        return -1;
    }
    std::cout << "Create socket successfully\t";
    std::cout << "socket_id -> " << sock << std::endl;

    // Create TCP server IPv4
    sockaddr_in saddr;
    unsigned port = 8080;
    if (argc > 1) {
        port = atoi(argv[1]);
    }
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port); // Little endian to big endian
    saddr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces

    // Bind
    if (bind(sock, (sockaddr *) &saddr, sizeof(saddr)) == SOCKET_ERROR) {
        std::cerr << "Bind port " << port << " failed" << std::endl;
        closesocket(sock);
#ifdef _WIN32
        WSACleanup();
#endif
        return -2;
    }
    std::cout << "Bind port " << port << " successfully!" << std::endl;

    // Listen
    if (listen(sock, 10) == SOCKET_ERROR) {
        std::cerr << "Listen failed" << std::endl;
        closesocket(sock);
#ifdef _WIN32
        WSACleanup();
#endif
        return -3;
    }
    std::cout << "Begin listening ..." << std::endl;

    // Accept connections
    while (true) {
        sockaddr_in caddr;
        socklen_t client_len = sizeof(caddr);
        int client_sock = accept(sock, (sockaddr *) &caddr, &client_len);
        if (client_sock == INVALID_SOCKET) {
            std::cerr << "Accept failed" << std::endl;
            continue;
        }
        std::cout << "Accepted client->" << client_sock << std::endl;
        char *client_ip = inet_ntoa(caddr.sin_addr);
        unsigned client_port = ntohs(caddr.sin_port);
        std::cout << "Client's IP->" << client_ip << ", port->" << client_port << std::endl;

        // Add new client
        {
            std::lock_guard<std::mutex> lock(clients_mutex);
            clients.push_back(client_sock);
        }
        TcpThread *th = new TcpThread();
        th->client_sock = client_sock;
        std::thread sth(&TcpThread::Main, th);
        sth.detach();
    }
}
